{:W('Cate/header')}
{:W('Cate/left')}
<!--内容部分-->
<div class="content">
    <div class="title">
        <p>设备列表</p>
        <i class="icon-angle-right"></i>
        <p class="active1"><a href="#" onClick="javascript :history.go(-1);" style="color:#515974">设备详情</a></p>
        <i class="icon-angle-right"></i>
        <p class="active">报警配置</p>
    </div>
    <div style="width:100%;padding:0 10px;">
        <div class="bj_list main_title2">
            <button class="bj_btn">保存设置</button>
            <ul class="clearfix">
                <li>
                    <em style="color: #1181cd;">资源名称</em> / 设备名称
                </li>
            </ul>
        </div>
    </div>
    <div class="admin_list clearfix">
        <div class="main">
            <div class="bj_main" style="padding-top:10px;">
                <div class="bj_main_one clearfix">
                    <div class="bj_left">
                        报警状态：
                    </div>
                    <div class="bj_right">
                        <label>
                            <if condition="$active eq 1">
                            <input type="checkbox" name="active" checked value="1">启用
                            <else/>
                            <input type="checkbox" name="active" value="1">启用
                            </if>
                        </label>
                    </div>
                </div>
                <div class="bj_main_one clearfix">
                    <div class="bj_left">
                        报警类型：
                    </div>
                    <div class="bj_right">
                        <label>
                            <input type="checkbox" name="box">全部
                        </label>
                        <volist name="type_arr" id="ta" key="k">
                            <label>
                                <?php if(in_array($k,$type)){ ?>
                                <input type="checkbox" name="boxcheck" checked value="{$k}">{$ta}
                                <?php } else { ?>
                                <input type="checkbox" name="boxcheck" value="{$k}">{$ta}
                                <?php } ?>
                            </label>
                        </volist>
                    </div>
                </div>
                <div class="bj_main_two clearfix">
                    <div class="bj_left">
                        报警时间：
                    </div>
                    <div class="bj_right">
                        <div class="r_title clearfix">
                            <span id="add_time" class="add active"><i class="icon-plus"></i>新增</span>
                            <span>
                                <em>星期</em>
                                <select name="week" id="week">
                                    <option value="">请选择</option>
                                    <option value="1">星期一</option>
                                    <option value="2">星期二</option>
                                    <option value="3">星期三</option>
                                    <option value="4">星期四</option>
                                    <option value="5">星期五</option>
                                    <option value="6">星期六</option>
                                    <option value="0">星期七</option>
                                </select>
                            </span>
                            <span>
                                <input class="time" type="text" id="begin_time" readonly value="" placeholder="开始时间">
                                <i class="icon-angle-down"></i>
                            </span>
                            <span>
                                <input class="time" type="text" id="end_time" readonly value="" placeholder="结束时间">
                                <i class="icon-angle-down"></i>
                            </span>
                            <button id="time_end">确定</button>
                            <button id="time_out">取消</button>
                        </div>
                        <div class="r_footer">
                            <volist name="weektime" id="we">
                                <span data-time='{$we.time_json}'><em>{$we.day_new}&nbsp;{$we.begintime_new}-{$we.endtime_new}</em><i class="icon-remove"></i></span>
                            </volist>
                        </div>
                    </div>
                </div>
                <div class="bj_main_three clearfix" style="margin:20px 0 50px 0;">
                    <div class="bj_left">
                        联动动作：
                    </div>
                    <div class="bj_right">
                        <div class="r_title clearfix">
                            <span id="add_bj" class="active"><i class="icon-plus"></i>新增</span>
                            <span id="edit_bj"><i class="icon-edit"></i>修改</span>
                            <span><i class="icon-remove"></i>删除</span>
                        </div>
                        <div class="r_footer">
                            <dl>
                                <dt>
                                    <span style="width:4%;"><input type="checkbox" name="box2"></span>
                                    <span style="width:32%;text-align:left;padding-left:20px;">资源名称</span>
                                    <span style="width:32%;">联动动作</span>
                                    <span style="width:32%;text-align:left;padding-left:20px;">动作说明</span>
                                </dt>
                                <volist name="linkcfginfo" id="li">
                                    <dd>
                                    <span style="width:4%;"><input data-json='{$li.link_json}' type="checkbox" name="box2check"></span>
                                    <span style="width:32%;text-align:left;padding-left:20px;">{$li.resid}</span>
                                    <span style="width:32%;">{$li.type_text}</span>
                                    <span style="width:32%;text-align:left;padding-left:20px;">
                                        <if condition="$li['type'] eq 'rec'">
                                            {$li.rectime}秒
                                        <else/>
                                            {$li.snappicnum}张，间隔{$li.snaptimediff}秒
                                        </if>
                                    </span>
                                    </dd>
                                </volist>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!--弹框-->
<!--添加子组织-->
<!--弹框-->
<!--新增客户-->
<div class="hk"></div>
<div class="add_group admin_list_box2" >
    <div class="add_group_title">
        <img src="__PUBLIC__/images/i_guanbi.png" class="icon-remove">新增联动动作
    </div>
    <div class="add_group_center">
        <ul>
            <li>
                <span>
                    <i>*</i>动作类型 :
                </span>
                <img src="__PUBLIC__/images/i_xiala.png" class="sj icon-sort-down">
                <select name="type">
                    <option value="">请选择动作类型</option>
                    <option value="snap">抓图</option>
                    <option value="rec">录像</option>
                </select>
            </li>
            <li>
                <span>
                    <i>*</i>动作设置 :
                </span>
                <img src="__PUBLIC__/images/i_xiala.png" class="sj icon-sort-down">
                <select name="snappicnum">
                    <option value="">请选择动作设置</option>
                    <option value="1">1张</option>
                    <option value="3">3张</option>
                    <option value="6">6张</option>
                    <option value="9">9张</option>
                </select>
                <select name="rectime" style="display: none">
                    <option value="">请选择动作设置</option>
                    <option value="10">10秒</option>
                    <option value="20">20秒</option>
                    <option value="40">40秒</option>
                    <option value="60">60秒</option>
                </select>
            </li>
            <li>
                <span>
                    <i>*</i>动作间隔 :
                </span>
                <img src="__PUBLIC__/images/i_xiala.png" class="sj icon-sort-down">
                <select name="snaptimediff">
                    <option value="">请选择动作间隔</option>
                    <option value="1">1秒</option>
                    <option value="2">2秒</option>
                    <option value="3">3秒</option>
                    <option value="5">5秒</option>
                </select>
            </li>
            <li>
                <span>
                    <i>*</i>联动资源 :
                </span>
                <img src="__PUBLIC__/images/i_xiala.png" class="sj icon-sort-down">
                <select name="resid" id="resid">
                    <option value="">请选择联动资源</option>
                </select>
            </li>
            <li>
                <span>
                    <i>*</i>码流 :
                </span>
                <img src="__PUBLIC__/images/i_xiala.png" class="sj icon-sort-down">
                <select name="streamType">
                    <option value="">请选择码流类型</option>
                    <option value="1">主码流</option>
                    <option value="2">子码流</option>
                </select>
            </li>
        </ul>
    </div>
    <div class="add_group_btn">
        <button>确定</button>
        <button>取消</button>
    </div>
</div>
<div class="add_group admin_list_box3" >
    <div class="add_group_title">
        <img src="__PUBLIC__/images/i_guanbi.png" class="icon-remove">修改联动动作
    </div>
    <div class="add_group_center">
        <ul>
            <li>
                <span>
                    <i>*</i>动作类型 :
                </span>
                <img src="__PUBLIC__/images/i_xiala.png" class="sj icon-sort-down">
                <select name="type">
                    <option value="">请选择动作类型</option>
                    <option value="snap">抓图</option>
                    <option value="rec">录像</option>
                </select>
            </li>
            <li>
                <span>
                    <i>*</i>动作设置 :
                </span>
                <img src="__PUBLIC__/images/i_xiala.png" class="sj icon-sort-down">
                <select name="snappicnum">
                    <option value="">请选择动作设置</option>
                    <option value="1">1张</option>
                    <option value="3">3张</option>
                    <option value="6">6张</option>
                    <option value="9">9张</option>
                </select>
                <select name="rectime" style="display: none">
                    <option value="">请选择动作设置</option>
                    <option value="10">10秒</option>
                    <option value="20">20秒</option>
                    <option value="40">40秒</option>
                    <option value="60">60秒</option>
                </select>
            </li>
            <li>
                <span>
                    <i>*</i>动作间隔 :
                </span>
                <img src="__PUBLIC__/images/i_xiala.png" class="sj icon-sort-down">
                <select name="snaptimediff">
                    <option value="">请选择动作间隔</option>
                    <option value="1">1秒</option>
                    <option value="2">2秒</option>
                    <option value="3">3秒</option>
                    <option value="5">5秒</option>
                </select>
            </li>
            <li>
                <span>
                    <i>*</i>联动资源 :
                </span>
                <img src="__PUBLIC__/images/i_xiala.png" class="sj icon-sort-down">
                <select name="resid">
                    <option value="">请选择联动资源</option>
                </select>
            </li>
            <li>
                <span>
                    <i>*</i>码流 :
                </span>
                <img src="__PUBLIC__/images/i_xiala.png" class="sj icon-sort-down">
                <select name="streamType">
                    <option value="">请选择码流类型</option>
                    <option value="1">主码流</option>
                    <option value="2">子码流</option>
                </select>
            </li>
        </ul>
    </div>
    <div class="add_group_btn">
        <button>确定</button>
        <button>取消</button>
    </div>
</div>
</body>
<script type="text/javascript">
    layui.use('laydate', function() {
        var laydate = layui.laydate;

        //执行一个laydate实例
        laydate.render({
            elem: '#begin_time', //指定元素
            format: 'HH:mm', //日期格式
            type:'time',
        });

        laydate.render({
            elem: '#end_time', //指定元素
            format: 'HH:mm', //日期格式
            type:'time',
        });
    });
    $(document).ready(function () {
        // 初始化联动资源
        $.post("{:U('/device_list/getSpecificResources')}",{},function(data){
            if( data.result != '0' || data.resources == null ){
                return false;
            }
            for(var i in data.resources){
                var _option = '<option value="'+data.resources[i]['id']+'">'+data.resources[i]['name']+'</option>';
                $('select[name="resid"]').append(_option);
            }
        })

        var oSheets = $('select[name="snappicnum"]');
        var oInterval = $('select[name="snaptimediff"]');
        $('select[name="type"]').change(function () {
            if($(this).val() == 'rec'){
                oSheets.hide().next().show();
                oInterval.attr("disabled",true);
            }else{
                oInterval.removeAttr("disabled");
                oSheets.show().next().hide();
            }
        })

        // 新增联动动作
        getPopup($('#add_bj'),$('.admin_list_box2'));
        // 报警类型全选
        selectCheckBox('input[name="box"]', 'input[name="boxcheck"]');
        // 联动动作全选
        selectCheckBox('input[name="box2"]', 'input[name="box2check"]');

        // 报警时间处理
        var oAdd_time = $('#add_time');
        oAdd_time.click(function () {
            $(this).hide().siblings().show();
        });
        $('#time_out').click(function () {
            oAdd_time.show().siblings().hide();
        });
        weektime = [];   // 存储报警时间
        var initial_time = '<?php echo $initial_time; ?>';   // 初始化报警时间
        initial_time = JSON.parse(initial_time);
        for(var t in initial_time){
            if(!isNaN(t)){   // 为了解决和下面的删除数组的方法出现冲突的问题（暂时不清楚为什么冲突）
                weektime.push(initial_time[t]);
            }
        }
        $('#time_end').click(function () {   // 数据显示在下面
            var _week = $('#week').val();
            var _weekName = $('#week option:checked').text();
            var _btime = $('#begin_time').val();
            var _etime = $('#end_time').val();
            if(_week == ''){
                layer.msg('请选择星期！',{icon:2,time:2000});
                return false;
            }
            if(!_btime){
                layer.msg('请选择开始时间！',{icon:2,time:2000});
                return false;
            }
            if(!_etime){
                layer.msg('请选择结束时间！',{icon:2,time:2000});
                return false;
            }
            // 结束时间大于开始时间
            var btime_split = _btime.split(':');
            var etime_split = _etime.split(':');
            var _bSecond = parseInt(btime_split[0])*3600+parseInt(btime_split[1])*60;
            var _eSecond = parseInt(etime_split[0])*3600+parseInt(etime_split[1])*60;
            if(_eSecond <= _bSecond){
                layer.msg('结束时间应大于开始时间！',{icon:2,time:2000});
                return false;
            }
            var _tmpData = {day:_week,begintime:_bSecond,endtime:_eSecond,livelong:_eSecond-_bSecond};
            for(var i in weektime){   // 如果星期选项相同，判断开始时间是否在已设置时间的范围内
                if(weektime[i]['day'] == _week){   // 判断时间是否有交叉
                    if(weektime[i]['begintime'] <=  _bSecond && weektime[i]['endtime'] >= _bSecond){
                        layer.msg('相同星期内，设置的时间出现交叉！',{icon:2,time:2000});
                        return false;
                    }
                    if(weektime[i]['begintime'] <=  _eSecond && weektime[i]['endtime'] >= _eSecond){
                        layer.msg('相同星期内，设置的时间出现交叉！',{icon:2,time:2000});
                        return false;
                    }
                    if( (weektime[i]['begintime'] <=  _bSecond && weektime[i]['endtime'] >= _eSecond) || (weektime[i]['begintime'] >=  _bSecond && weektime[i]['endtime'] <= _eSecond) ){
                        layer.msg('相同星期内，设置的时间出现交叉！',{icon:2,time:2000});
                        return false;
                    }
                }
            }
            weektime.push(_tmpData);
            // 将报警时间插入到下面
            var _span = "<span data-time='"+JSON.stringify(_tmpData)+"'><em>"+_weekName+"&nbsp;"+_btime+"-"+_etime+"</em><i class='icon-remove'></i></span>";
            $('.bj_main_two .r_footer').append(_span);
            oAdd_time.show().siblings().hide();
            oAdd_time.parent().find('select,input').val('');   // 初始化选项
        });

        // 点击删除报警时间,并删除全局变量weektime中的对应数据
        $('.bj_main_two .r_footer').on('click','.icon-remove',function(){
            var _thisTime = $(this).parents('span').attr('data-time');
            _thisTime = JSON.parse(_thisTime);
            for(var i in weektime){
                if(weektime[i]['day'] == _thisTime['day'] && weektime[i]['begintime'] == _thisTime['begintime'] && weektime[i]['endtime'] == _thisTime['endtime']){
                    weektime.baoremove(i);
                    $(this).parents('span').remove();
                    break;   // 终止循环
                }
            }
        })

        // 新增联动动作
        linkcfginfo = [];   // 存储联动动作数据
        linkcfginfo['snap'] = [];   // 存储抓图数据
        linkcfginfo['rec'] = [];   // 存储录像数据
        var initial_link_rec = '<?php echo $initial_rec; ?>';   // 初始化录像数据
        initial_link_rec = JSON.parse(initial_link_rec);
        for(var r in initial_link_rec){
            if(!isNaN(r)){   // 为了解决和下面的删除数组的方法出现冲突的问题（暂时不清楚为什么冲突）
                linkcfginfo['rec'].push(initial_link_rec[r]);
            }
        }
        var initial_link_snap = '<?php echo $initial_snap; ?>';   // 初始化抓图数据
        initial_link_snap = JSON.parse(initial_link_snap);
        for(var s in initial_link_snap){
            if(!isNaN(s)){   // 为了解决和下面的删除数组的方法出现冲突的问题（暂时不清楚为什么冲突）
                linkcfginfo['snap'].push(initial_link_snap[s]);
            }
        }
        flag = true;   // 确保每个动作执行完成后才能再次点击
        $('.admin_list_box2 .add_group_btn button').eq(0).on('click',function(){
            if(!flag){   // 每次只能点击一次
                return false;
            }
            var _conf = get_data('.admin_list_box2');
            if(!_conf){
                return false;
            }
            // 验证是否已经存在
            var _linkcfginfo = linkcfginfo[_conf['type']];
            for(var i in _linkcfginfo){
                if(_linkcfginfo[i]['resid'] == _conf['resid']){
                    layer.msg('该联动资源已设置该动作！',{icon:2,time:2000});
                    return false;
                }
            }
            flag = false;
            var _tmpConf = '';
            if(_conf['type'] == 'snap') {   // 抓图
                _tmpConf = {resid:_conf['resid'],snappicnum:_conf['snappicnum'],snaptimediff:_conf['snaptimediff'],streamType:_conf['streamType']};
            } else {
                _tmpConf = {resid:_conf['resid'],rectime:_conf['rectime'],streamType:_conf['streamType']};
            }
            linkcfginfo[_conf['type']].push(_tmpConf);
            var _box2check = "<dd>" +
                     "<span style='width:4%;'><input data-json='"+JSON.stringify(_conf)+"' type='checkbox' name='box2check'></span>" +
                     '<span style="width:32%;text-align:left;padding-left:20px;">'+_conf['resid_text']+'</span>' +
                     '<span style="width:32%;">'+_conf['type_text']+'</span>' +
                     '<span style="width:32%;text-align:left;padding-left:20px;">动作说明</span>' +
                     '</dd>';
            // 获取已有的动作，相同资源的动作放在一起
            var _aHave = $('.bj_main_three dd');
            var _num = false;
            _aHave.each(function(){
                var _json = $(this).find('[name="box2check"]').attr('data-json');
                _json = JSON.parse(_json);
                if(_json.resid == _conf['resid']){
                    $(this).after(_box2check);
                    _num = true;
                    return false;
                }
            })
            if(!_num){
                $('.bj_main_three dl').append(_box2check);
            }
            close();
            flag = true;
        });

        // 修改联动动作
        $('.admin_list_box3 .add_group_btn button').eq(0).on('click',function(){
            var _conf = get_data('.admin_list_box3');
            if(!_conf){
                return false;
            }
            var _checked = $('.bj_main_three input[name="box2check"]:checked');
            // 根据resid修改linkcfginfo中存储的对应数据
            for(var i in linkcfginfo[_conf['type']]){
                if(isNaN(i) || _conf['resid'] != linkcfginfo[_conf['type']][i]['resid']){
                    continue;
                }
                if(_conf['type'] == 'rec'){  // 录像
                    linkcfginfo['rec'][i]['rectime'] = _conf['rectime'];
                    linkcfginfo['rec'][i]['streamType'] = _conf['streamType'];
                    // 修改动作说明
                    _checked.parents('dd').find('span:last').text(_conf['rectime_text']);
                    break;
                }
                if(_conf['type'] == 'snap'){  // 抓图
                    linkcfginfo['snap'][i]['snappicnum'] = _conf['snappicnum'];
                    linkcfginfo['snap'][i]['snaptimediff'] = _conf['snaptimediff'];
                    linkcfginfo['snap'][i]['streamType'] = _conf['streamType'];
                    // 修改动作说明
                    _checked.parents('dd').find('span:last').text(_conf['snappicnum_text']+',间隔'+_conf['snaptimediff_text']);
                    break;
                }
            }
            // 修改选中的动作data-json属性值
            _checked.attr('data-json',JSON.stringify(_conf));
            close();
        })

        // 删除选中的联动动作
        $('.bj_main_three .bj_right span:last-child').on('click',function(){
            // 判断是否有选中的值
            var _checked = $('.bj_main_three input[name="box2check"]:checked');
            if(!_checked.length){
                layer.msg('请选择要删除的资源！',{icon:2,time:2000});
                return false;
            }
            // 删除选中的节点，同时删除全局变量linkcfginfo中对应的数据
            _checked.each(function(){
                var _thisData = $(this).attr('data-json');
                _thisData = JSON.parse(_thisData);
                for(var i in linkcfginfo[_thisData['type']]){
                    if(linkcfginfo[_thisData['type']][i]['resid'] == _thisData['resid']){
                        linkcfginfo[_thisData['type']].baoremove(i);
                        $(this).parents('dd').remove();
                        break;   // 终止循环
                    }
                }
            })
        })

        // 保存设置
        $('.main_title2 .bj_btn').on('click',function(){
            var _active = 0;
            if($('[name="active"]').is(':checked')){
                _active = 1;
            }
            var _boxcheck = $('[name="boxcheck"]:checked');
            if(!_boxcheck.length){
                layer.msg('请选择报警类型！',{icon:2,time:2000});
                return false;
            }
            var _type = '';
            _boxcheck.each(function(){
                _type += $(this).val()+',';
            })
            var _resid = "<?php echo $_GET['resids']; ?>";
            var _post = {
                resid:_resid,
                active:_active,
                type:_type,
                weektime:weektime,
                rec:linkcfginfo['rec'],
                snap:linkcfginfo['snap'],
            };
            $.post("{:U('device_list/SettingResourceAllocation')}",_post,function(data){
                if(data.result == '0'){
                    layer.msg('报警配置成功！',{icon:1,time:2000},function(){
                        history.back()
                    });
                } else {
                    layer.msg(data.msg,{icon:2,time:2000});
                }
            })
        })

    })

    /*
     * 方法:Array.baoremove(dx)
     * 功能:删除数组元素.
     * 参数:dx删除元素的下标.
     * 返回:在原数组上修改数组.
     */
    Array.prototype.baoremove = function(dx)
    {
        if(isNaN(dx)||dx>this.length){return false;}
        this.splice(dx,1);
    }

    /**
     * 获取input框的数据
     * @param string obj 节点属性值
     */
    function get_data(obj)
    {
        var _input = $(obj).find('input,select').not(':hidden');
        var _conf = {};
        _input.each(function(i){
            _conf[_input.eq(i).attr('name')] = _input.eq(i).val();
            _conf[_input.eq(i).attr('name')+'_text'] = _input.eq(i).find('option:selected').text();
        })
        for(var i in _conf){
            if(!_conf[i] && i.indexOf('_text') == '-1' && i != 'snaptimediff'){
                layer.msg('请把表单填写完整！',{icon:2,time:2000});
                return false;
            }
            if(_conf[i]['type'] == 'snap' && !_conf[i]['snaptimediff']){
                layer.msg('请把表单填写完整！',{icon:2,time:2000});
                return false;
            }
        }
        return _conf;
    }

    // 修改联动动作
    (function () {
        var oDome = $('.admin_list_box3');
        $('.bj_main_three #edit_bj').on('click',function(){
            var _checked = $('.bj_main_three input[name="box2check"]:checked');
            if(_checked.length != 1){
                layer.msg('请选择其中一个动作进行修改！',{icon:2,time:2000});
                return false;
            }
            // 修改联动动作
            var _json = _checked.attr('data-json');
            _json = JSON.parse(_json);
            oDome.find('[name="type"]').val(_json.type);
            oDome.find('[name="type"]').attr('disabled',true);
            if(_json.type == 'rec'){
                oDome.find('[name="rectime"]').val(_json.rectime);
                oDome.find('[name="rectime"]').attr('style','display:block');
                oDome.find('[name="snappicnum"]').attr('style','display:none');
                oDome.find('[name="snaptimediff"]').attr('disabled',true).val('');
            } else {
                oDome.find('[name="snappicnum"]').val(_json.snappicnum);
                oDome.find('[name="snappicnum"]').attr('style','display:block');
                oDome.find('[name="rectime"]').attr('style','display:none');
                oDome.find('[name="snaptimediff"]').attr('disabled',false).val(_json.snaptimediff);
            }
            oDome.find('[name="resid"]').attr('disabled',true).val(_json.resid);
            oDome.find('[name="streamType"]').val(_json.streamType);
            oDome.show();
            $('.hk').fadeIn(200);
        });

        $('.hk').click(function () {
            oDome.hide(200);
            $('.hk').fadeOut(200);
        });
        oDome.find('.icon-remove').click(function () {
            oDome.hide(200);
            $('.hk').fadeOut(200);
        });
    })();
</script>
</html>